<template>
  <div class="employees-container">
    <div class="app-container">
      <page-tools>
        <template #left>
          <span>总记录数: {{ total }} 条</span>
        </template>
        <template #right>
          <el-button type="warning" size="small" @click="$router.push('/import')">excel导入</el-button>
          <el-button type="danger" size="small" @click="handleDownload">excel导出</el-button>
          <el-button type="primary" size="small" @click="showDialog = true">新增员工</el-button>
        </template>
      </page-tools>

      <el-card style="margin-top: 10px;">
        <el-table :data="list" border :default-sort="{prop: 'date', order: 'descending'}">
          <el-table-column label="序号" type="index" />
          <el-table-column label="姓名" prop="username" />
          <el-table-column label="头像">
            <template slot-scope="scope">
              <img :src="scope.row.staffPhoto" width="100">
            </template>
          </el-table-column>
          <el-table-column label="工号" prop="workNumber" />
          <el-table-column label="聘用形式">
            <template v-slot="{row}">
              <div>
                {{ formatData(row.formOfEmployment) }}
              </div>
            </template>
          </el-table-column>
          <el-table-column label="部门" prop="departmentName" />
          <el-table-column label="入职时间" prop="correctionTime" sortable />
          <!-- <el-table-column label="账户状态" /> -->
          <el-table-column label="操作" width="280">
            <template v-slot="{row}">
              <el-button type="text" size="small" @click="$router.push(`/employees/detail?userId=${row.id}`)">查看</el-button>
              <el-button type="text" size="small" @click="assignEmp(row.id)">分配角色</el-button>
              <el-button v-allow="'point-user-delete'" type="text" size="small" @click="hDel(row.id)">删除</el-button>
            </template>
          </el-table-column>
        </el-table>
        <!-- 分页组件 -->
        <el-row type="flex" justify="center" align="middle" style="height: 60px">
          <el-pagination
            :current-page="page"
            :page-size="size"
            layout="prev, pager, next"
            :total="total"
            @current-change="handleCurrentChange"
          />
        </el-row>
      </el-card>
      <el-dialog title="新增员工" :visible.sync="showDialog">
        <addor-edit v-if="showDialog" @success="hAdd" @close="showDialog = false" />
      </el-dialog>
      <el-dialog title="分配角色" :visible.sync="assignEmpDialog">
        <assignRole :cur-id="curId" @success="assignEmpDialog = false" />
      </el-dialog>
    </div>
  </div>
</template>

<script>
import employeesNum from '@/constant/employees'
import assignRole from './assignRole.vue'
const hireType = employeesNum.hireType.reduce((acc, item) => {
  acc[item.id] = item.value
  return acc
}, {})
import { delEmployees, getEmployees } from '@/api/employees'
import addorEdit from './empDialog.vue'
export default {
  components: {
    addorEdit,
    assignRole
  },
  data() {
    return {
      page: 1,
      size: 10,
      list: [],
      total: 0,
      showDialog: false,
      assignEmpDialog: false,
      curId: ''
    }
  },
  created() {
    this.lodeEmployees()
  },
  methods: {
    assignEmp(id) {
      this.curId = id
      this.assignEmpDialog = true
    },
    hAdd() {
      this.total++
      const maxPage = Math.ceil(this.total / this.size)
      this.page = maxPage
      this.lodeEmployees()
      this.showDialog = false
    },
    hDel(id) {
      this.$confirm('您确定要删除员工吗', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(async() => {
        const res = await delEmployees(id)
        if (res.code === 10000) {
          this.$message.success(res.message)
          if (this.list.length === 1) {
            this.page--
            if (this.page <= 0) {
              this.page = 1
            }
          }
          this.lodeEmployees()
        }
      })
    },
    formatData(id) {
      return hireType[id] || '未知'
    },
    async lodeEmployees() {
      try {
        const res = await getEmployees({ page: this.page, size: this.size })
        if (res.code === 10000) {
          this.$message.success(res.message)
          this.list = res.data.rows
          this.total = res.data.total
        }
        // 保存数据
      } catch (err) {
        console.log(err)
      }
    },
    handleCurrentChange(val) {
      this.page = val
      this.lodeEmployees()
    },
    handleDownload() {
      // import('@/vendor/Export2Excel')  懒加载的方式导入一个模块， 返回值是一个promise实例
      import('@/vendor/Export2Excel').then(excel => {
        // excel指的模块对象，那么就可以使用这个模块对象去调用这个模块里面的函数或者访问变量   excel.函数名()
        // const tHeader = ['Id', 'Title', 'Author', 'Readings', 'Date']
        // const filterVal = ['id', 'title', 'author', 'pageviews', 'display_time']
        // const list = this.list
        // console.log(list, 'listaaaaaaaaaaaaaaaaaaaa')
        // const data = this.formatJson(filterVal, list)
        // console.log(data, 'dataaaaaaaaaaaaaaaaa')
        // const data = [['刘备', 100],
        //   ['关羽', 500]]
        const { tHeader, data } = this.transZhKeyToExcel(this.list)
        excel.export_json_to_excel({
          header: tHeader,
          data,
          filename: this.filename,
          autoWidth: this.autoWidth,
          bookType: this.bookType
        })
      })
    },
    transZhKeyToExcel(list) {
      const mapInfo = {
        'id': '编号',
        'password': '密码',
        'mobile': '手机号',
        'username': '姓名',
        'timeOfEntry': '入职日期',
        'formOfEmployment': '聘用形式',
        'correctionTime': '转正日期',
        'workNumber': '工号',
        'departmentName': '部门',
        'staffPhoto': '头像地址'
      }
      // 1.判断数组有没有数据 没有数据直接终止执行
      const one = list[0]
      if (!one) return
      // 2.获得 中文 tHeader 表格头部
      // Object.keys(mapInfo) 取到英文名称
      // 通过map遍历数组 根据英文名称找到对应的中文名称 返回 新数组
      const tHeader = Object.keys(one).map(enkey => {
        return mapInfo[enkey]
      })
      // 2.获得 表格数据
      // 遍历数组 使用 Object.values(item) 获取数据
      const data = list.map(item => {
        return Object.values(item)
      })
      return { tHeader, data }
    }
  }
}
</script>

<style>

</style>
